package com.dyoud.api.upload.controller;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.douyoudian.utils.FileUtils;
import org.jboss.netty.util.HashedWheelTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dyoud.api.ReturnInfo;
import com.dyoud.core.ResponseBean;
import com.dyoud.file.api.service.FileUploadService;

/**
 * 上传
 * 
 * @author Jonathan
 * @date 2018/03/01
 *
 */
@RestController
@RequestMapping("upload")
public class UploadController {

    @Value("${pic_prefix}")
    private String picPrefix;
    private static final Logger log = LoggerFactory.getLogger(UploadController.class);
    @Reference
    private FileUploadService fileUploadService;

    @RequestMapping(value = "/put", method = RequestMethod.POST)
    public ResponseBean put(@RequestParam("pic") MultipartFile multipartFile) {
        ResponseBean response = new ResponseBean();
        try {
            InputStream input = multipartFile.getInputStream();
            // 原始文件名
            String originalName = multipartFile.getOriginalFilename();
            String suffix = FileUtils.getSuffix(originalName);
            byte[] data = IOUtils.toByteArray(input);
            String key = fileUploadService.upload(data, FileUtils.getNewFileName() + suffix);
            response.success(picPrefix + key);
        } catch (IOException e) {
            log.error(ReturnInfo.UPLOAD_FILE_MSG, e);
            response.fail(ReturnInfo.UPLOAD_FILE_CODE, ReturnInfo.UPLOAD_FILE_MSG);
        }
        return response;
    }

}
